package com.library.view.components;

import com.library.controller.AdminUserController;
import com.library.pojo.dto.user.UserDTO;
import com.library.pojo.dto.user.UserPageQueryDTO;
import com.library.result.Result;
import com.library.utils.StringUtils;
import io.yukk1o.easytermui.base.BasePanel;
import io.yukk1o.easytermui.base.Listener.InteractiveListener;
import io.yukk1o.easytermui.component.Button;
import io.yukk1o.easytermui.component.InputBox;
import io.yukk1o.easytermui.component.Text;

import java.util.LinkedHashMap;

/**
 * 新增用户弹窗
 * <p>
 * 包含组件:
 * 弹窗内：取消按钮、输入框（用户名/密码/权限）、确认按钮
 * <p>
 * 交互流程:
 * 1. 点击取消/按ESC → 关闭弹窗；
 * 2. 点击输入框可调整光标位置，点击确认按钮 → 向数据库新增用户，关闭弹窗。
 */
public class UserAddDialog extends BasePanel {

    /**
     * 构造「嵌套Panel」（相对坐标）
     *
     * @param relX   相对于父Panel的X坐标
     * @param relY   相对于父Panel的Y坐标
     */
    Text title_Text, user_Name_Text, user_Password_Text;
    InputBox user_Name_Input, user_Password_Input;
    Button confirm_button, cancel_button;
    AdminUserController adminUserController;
    UserDTO  userDTO;

    public UserAddDialog(int relX, int relY) {
        super(relX, relY, 40, 12);
        init();
    }

    public void init() {
        adminUserController = new AdminUserController();
        userDTO = new UserDTO();

        title_Text = new Text(16, 2, 4, 1, "添加用户");
        addComponent(title_Text);

        user_Name_Text = new Text(8, 4, 5, 1, "用户名:");
        user_Password_Text = new Text(8, 6, 5, 1, "  密码:");
        addComponent(user_Name_Text);
        addComponent(user_Password_Text);

        user_Name_Input = new InputBox(15, 4, 17);
        user_Password_Input = new InputBox(15, 6, 17);
        addComponent(user_Name_Input);
        addComponent(user_Password_Input);



        confirm_button = new Button(24, 9, "添加", (button) -> {
            userDTO.setUsername(user_Name_Input.getValue());
            userDTO.setPassword(user_Password_Input.getValue());
            Result<String> result = adminUserController.insert(userDTO);

            if(result.getCode() == 1){//成功
                InteractiveListener listener = (InteractiveListener) getBindData();
                listener.stopListener();
            }else{//失败
                //todo 失败提示,需要补充代码逻辑
                Text hint = new Text(18,7,10,1,result.getMsg());
                addComponent(hint);
                InteractiveListener listener = (InteractiveListener) getBindData();
                listener.stopListener();
            }
        });
        addComponent(confirm_button);

        cancel_button = new Button(8, 9, "取消", (button -> {
            InteractiveListener listener = (InteractiveListener) getBindData();
            listener.stopListener();
        }));
        addComponent(cancel_button);
    }

    @Override
    public void renderContext() {
        drawBorder();
        super.renderContext();
    }
}
